package cn.rongdao.jrkabao.base;

import android.content.Intent;
import android.text.TextUtils;

import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.util.FRToast;
import com.moxie.client.manager.MoxieSDK;
import com.moxie.client.model.MxParam;

import cn.rongdao.jrkabao.bean.information.apply.ApplyInfoBean;
import cn.rongdao.jrkabao.constant.InfoConstant;
import cn.rongdao.jrkabao.model.SendVerificateTypeToServerModel;
import cn.rongdao.jrkabao.model.information.apply.ZhimaUrlModel;
import cn.rongdao.jrkabao.ui.IdentificationVerificate.IdentificationWithValidationItem.IdentificationWithCreditCardActivity;
import cn.rongdao.jrkabao.ui.IdentificationVerificate.IdentificationWithValidationItem.IdentificationWithFublicFundActivity;
import cn.rongdao.jrkabao.ui.IdentificationVerificate.IdentificationWithValidationItem.IdentificationWithSocialSecurityActivity;
import cn.rongdao.jrkabao.ui.IdentificationVerificate.LoanIdentificationActivity;
import cn.rongdao.jrkabao.ui.information.AddCardActivity;
import cn.rongdao.jrkabao.ui.information.BasicInfoActivity;
import cn.rongdao.jrkabao.ui.information.listener.OnItemActionListener;
import cn.rongdao.jrkabao.ui.takephoto.CommonValidateIdCardPicActivity;
import cn.rongdao.jrkabao.ui.takephoto.OtherImageDataActivity;
import cn.rongdao.jrkabao.ui.webview.WebViewActivity;
import cn.rongdao.jrkabao.util.moxie.MoXieManager;

/**
 * Created by jiangyongxing on 2017/5/11.
 * 描述：
 */

public abstract class FRBaseLooperRequestActivity extends BaseAutoFinishActivity {

    public boolean mIsRunning = false;

    private Intent mIntent;
    protected MoXieManager moXieManager;

    @Override
    protected void initView() {
        super.initView();
        moXieManager = new MoXieManager(this);
        initListener();
    }

    private void initListener() {
        moXieManager.setOnMoXieReturnListener(new MoXieManager.OnMoXieReturnListener() {
            @Override
            public void looperMethod(String email) {
                mIsRunning = true;
                baseLooperMethod();
            }

            @Override
            public void successReturn(String email) {

            }
        });
    }

    protected void startRun() {
        moXieManager.startRun();
    }

    /**
     * 需要轮询的方法
     */
    protected void baseLooperMethod() {

    }

    @Override
    public void onStop() {
        super.onStop();
        stopRunning();
    }

    public void stopRunning() {
        if (null != moXieManager) {
            moXieManager.onStop();
            mIsRunning = false;
        }
    }

    public void sendVerificateType2Server(String materialCode) {
        SendVerificateTypeToServerModel.getInstance().execute(materialCode, new FRBaseObserver<String>(this) {
            @Override
            protected void onBaseNext(String data) {
            }

            @Override
            protected void onBaseError(Throwable t) {
                handingExceptions(t, false);
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
            case InfoConstant.RESULT_CODE_PUBLIC_FUND:
                sendVerificateType2Server("public_fund");
                break;
        }
    }

    /**
     * 魔蝎SDK成功返回之后的操作，如果子类需要的话，就重写这个方法
     */
    protected void successReturn() {

    }

    protected void startMoxieActivity() {
        moXieManager.startMoXieWithMxParam(null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //用来清理数据或解除引用
        MoxieSDK.getInstance().clear();
    }

    protected OnItemActionListener listener = new OnItemActionListener() {

        @Override
        public void onBasicInfoClick(int status) {//需要判断是否验证了基本信息
            if (promptsTheUserThroughStatus(status, "您已验证过基本信息，无需再次验证", InfoConstant.BASIC_INFO))
                return;
            toBasicInfoActivity();
        }

        @Override
        public void onIdentityInfoClick(int status) {
            if (promptsTheUserThroughStatus(status, "您已验证过身份信息", InfoConstant.IDENTITY_INFO)) {
                return;
            }
            toValidateIndentificationCardActivity();

        }

        @Override
        public void onCreditVerifyClick(int status) {
            if (promptsTheUserThroughStatus(status, "您已验证过信用卡，无需再次验证", InfoConstant.CREDIT_VERIFY))
                return;
            toCreditCardActivity();
        }

        @Override
        public void onDepositCardClick(int status) {
            if (promptsTheUserThroughStatus(status, "您已验证过储蓄卡，无需再次验证")) return;
            toAddInfoCard();
        }


        @Override
        public void onECVerifyClick(int status) {
            if (promptsTheUserThroughStatus(status, "您已验证过淘宝，无需再次验证")) return;
            toEcVerifyActivity();
        }

        @Override
        public void onIdentityPicClick(int status) {
            if (promptsTheUserThroughStatus(status, "您已验证过身份证照片，无需再次验证")) return;
            toValidateIndentificationCardPicActivity();
        }

        @Override
        public void onOperatorVerifyClick(int status) {
            if (promptsTheUserThroughStatus(status, "您已验证过手机号，无需再次验证")) return;
            toOperatorVerifyActivity();
        }

        @Override
        public void onPersonalCreditClick(int status) {
            if (promptsTheUserThroughStatus(status, "您已验证过个人征信，无需再次验证")) return;
            toPersonalCreditActivity();
        }

        @Override
        public void onPublicAccumulationFundClick(int status) {
            if (promptsTheUserThroughStatus(status, "您已验证过公积金，无需再次验证", InfoConstant.PUBLIC_ACCUMULATION_FUND))
                return;
            toPublicAccumulationFundActivity();
        }

        @Override
        public void onZhimaClick(int status) {
            zhimaCheck(status);
        }

        @Override
        public void onOtherFilmprofileClick(int status) {
            toOtherImageDataActivity();
        }

        @Override
        public void onAlipayClick(int status) {
            if (promptsTheUserThroughStatus(status, "您已验证过支付宝，无需再次验证")) return;
            toAliPayActivity();
        }

        @Override
        public void onJingdongClick(int status) {
            if (promptsTheUserThroughStatus(status, "您已验证过京东，无需再次验证")) return;
            toJingDongActivity();
        }

        @Override
        public void onItemClickWithUrl(int status, String jump_url, String code) {
            if (promptsTheUserThroughStatus(status, "您已完善该项资料")) return;
            WebViewActivity.startWithProductId(getActivity(), jump_url, getProductId());
        }

        @Override
        public void onSecurityVerifyClick(int status) {
            if (promptsTheUserThroughStatus(status, "您已验证过社保，无需再次验证")) return;
            toSecurityVerifyActivity();
        }
    };

    /**
     * 通过状态来提示用户操作
     *
     * @param status
     * @return
     */
    protected boolean promptsTheUserThroughStatus(int status, String message) {
        return promptsTheUserThroughStatus(status, message, "");
    }

    /**
     * 通过状态来提示用户操作
     *
     * @param status
     * @return
     */
    protected boolean promptsTheUserThroughStatus(int status, String message, String code) {
        String cateId = getCateId();
        if (openAFillableItemEntry(code, cateId, status)) return false;
        if (getUserFirstFillInItem() != null && getUserFirstFillInItem().getStatus() != 1) {
            switch (getUserFirstFillInItem().getCode()) {
                case InfoConstant.IDENTITY_INFO:
                    FRToast.showToastSafe("请先进行实名认证");
                    toValidateIndentificationCardActivity();
                    break;
                case InfoConstant.CREDIT_VERIFY:
                    FRToast.showToastSafe("请先进行信用卡验证");
                    toCreditCardActivity();
                    break;
                case InfoConstant.PUBLIC_ACCUMULATION_FUND:
                    FRToast.showToastSafe("请先进行公积金验证");
                    toPublicAccumulationFundActivity();
                    break;
                default:
                    FRToast.showToastSafe("请先进行实名认证");
                    toValidateIndentificationCardActivity();
                    break;
            }
            return true;
        }
        //基本信息填写完成还是允许修改
        if (InfoConstant.BASIC_INFO.equals(code))
            return false;
        return disallowToModify(status, message);
    }

    /**
     * 开放一个第一次可以填写的入口（比如信用卡，公积金，身份信息未填写状态一定是要先填写的）
     *
     * @param code
     * @param cateId
     * @return
     */
    private boolean openAFillableItemEntry(String code, String cateId, int status) {
        //当前的item为3个必须先填的项目，然后是没有填写过的
        if (code.equals(getUserFirstFillInItem().getCode()) && getUserFirstFillInItem().getStatus() != 1) {
            return true;
        }

        //判断是我的额度界面的页面，cateid为空，然后必填项是身份信息，公积金和信用卡也可以点击去,如果已经验证了就不行
        if (currentPageIsMyQuotaActivity(code, cateId, status)) return true;
        return false;
    }

    /**
     * 如果当前的Activity是我的人额度界面，此时的cateid为空，code为InfoConstant.IDENTITY_INFO
     * <p>
     * 需求：除去身份信息可以先填，信用卡和公积金也可以先填写，因为在这两个页面里面是有身份信息这一项的。当然还要加上这两项并没有被填写过
     *
     * @param code
     * @param cateId
     * @param status
     * @return
     */
    private boolean currentPageIsMyQuotaActivity(String code, String cateId, int status) {
        if (TextUtils.isEmpty(cateId) && InfoConstant.IDENTITY_INFO.equals(getUserFirstFillInItem().getCode()) && status != 1) {
            if (InfoConstant.CREDIT_VERIFY.equals(code) || InfoConstant.PUBLIC_ACCUMULATION_FUND.equals(code))
                return true;
        }
        return false;
    }

    /**
     * 通过状态来判断是否不允许用户修改
     *
     * @param status
     * @param message
     * @return
     */
    private boolean disallowToModify(int status, String message) {
        if (status == 1) {
            FRToast.showToastSafe(message);
            return true;
        }
        return false;
    }


    //用户第一项填写的资料状态（默认是身份信息，子类可以修改返回值）
    protected ApplyInfoBean.FirstItemBean getUserFirstFillInItem() {
        return new ApplyInfoBean.FirstItemBean(InfoConstant.IDENTITY_INFO, 1);
    }


    protected void toSecurityVerifyActivity() {
        IdentificationWithSocialSecurityActivity.start(this, getProductId());
    }

    protected void toJingDongActivity() {
        moXieManager.initMoXieContent(MxParam.PARAM_TASK_JINGDONG);
        startMoxieActivity();
    }

    protected void zhimaCheck(int status) {
        if (promptsTheUserThroughStatus(status, "您已验证过芝麻信用，无需再次验证")) return;
        ZhimaUrlModel.getInstance().execute(new FRBaseObserver<String>(this, "正在跳转") {
            @Override
            protected void onBaseNext(String data) {
                mIntent = new Intent(getActivity(), WebViewActivity.class);
                mIntent.putExtra("url", data);
                startActivity(mIntent);
            }
        });
    }

    protected void toOtherImageDataActivity() {
        startActivity(OtherImageDataActivity.class);
    }

    protected void toPublicAccumulationFundActivity() {
        IdentificationWithFublicFundActivity.start(this, getCateId(), getProductId(), getPageSource(), getLoanName());
    }


    protected void toPersonalCreditActivity() {
        moXieManager.initMoXieContent(MxParam.PARAM_TASK_ZHENGXIN);
        startMoxieActivity();
    }

    protected void toAliPayActivity() {
        moXieManager.initMoXieContent(MxParam.PARAM_TASK_ALIPAY);
        startMoxieActivity();
    }

    /**
     * 运营商
     */
    protected void toOperatorVerifyActivity() {
        moXieManager.initMoXieContent(MxParam.PARAM_TASK_CARRIER);
        startMoxieActivity();
    }

    protected void toEcVerifyActivity() {
        moXieManager.initMoXieContent(MxParam.PARAM_TASK_TAOBAO);
        startMoxieActivity();
    }

    protected void toAddInfoCard() {
        startActivity(AddCardActivity.class);
    }

    protected void toCreditCardActivity() {
//        CreditCardVerificationActivity.start(this, mCateId, mProductId, "");
        IdentificationWithCreditCardActivity.start(this, getCateId(), getProductId(), getPageSource(), getLoanName());
    }

    protected void startActivity(Class clazz) {
        mIntent = new Intent(this, clazz);
        startActivity(mIntent);
    }

    protected void toValidateIndentificationCardActivity() {
        LoanIdentificationActivity.start(getActivity());
    }

    protected void toValidateIndentificationCardPicActivity() {
        CommonValidateIdCardPicActivity.start(getActivity());
    }

    /**
     * 跳转到基本信息界面
     */
    protected void toBasicInfoActivity() {
        BasicInfoActivity.start(this, getProductId());
    }

    protected String getCateId() {
        return "";//默认值
    }

    protected String getProductId() {
        return "";//默认值
    }

    protected String getPageSource() {
        return "0";//默认值

    }

    protected String getLoanName() {
        return "";
    }
}
